﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusCompView
{
    public class FinPlusGridColHelper : FinPlusControl
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        public ColHelpers ColMaps { get; private set; }

        private enum Params {QuoteInstrument, LinkedId }
        private FinPlusGroupGrid _grid;
       
        //constuct
        public FinPlusGridColHelper(IDictionary<string, string[]> colFormats = null, IDictionary<string, string[]> colTypes = null, string[] enabledCols = null, IDictionary<string, string[]> colLinks = null)
        {
            ColMaps = new ColHelpers(colTypes, enabledCols, colLinks, colFormats);
            IsValid = true;
        }

        //public
        public void Link(FinPlusGroupGrid grid, RoutedEventHandler filterbarAdd,  RoutedEventHandler filterbarRemove)
        {
            try
            {
                _grid = grid;
                ColMaps.Load(grid, LinkedId, filterbarAdd, filterbarRemove);
            }
            catch(Exception e)
            {
                IsValid = Level.Warning.Log(Id, Config, e.Message, e);
            }
        }

        public DataGridTemplateColumn GetTemplate(string name, string type)
        {
            if (ColMaps.HasCol(name)) 
                return null; //already added

            var colMap = ColMaps.GetMap(name, type);
            LinkEvents(colMap, name);//links events re popups
            ColMaps.ListColNames.Add(name);

            var col = colMap.GetTemplate(TagProperty, name);
            return col;
        }

        public void SetColState(DataGrid dataGrid, FinPlusColSelectBar colSelectBar, string states)
        {
            var stateArray = states.ToListOfArrays(',', "{}", null);
            
            foreach (var state in stateArray)
            {
                try
                {
                    var f = dataGrid.Columns.Where(c => c.GetValue(TagProperty).ToString() == state[0]);
                    if(f.Count() < 1) 
                        continue;
                    
                    var col = f.First();
                    col.DisplayIndex = int.Parse(state[1]);
                    
                    var width = double.NaN;
                    double.TryParse(state[2], out width);
                    col.Width = width;
                    col.Visibility = state[3].EnumParse<Visibility>(Visibility.Visible);
                    
                    if (colSelectBar != null) 
                        colSelectBar.AddButton(state[0], col.Visibility == Visibility.Collapsed);
                }
                catch (Exception e)
                {
                    Level.Warning.Log(Id, Config, e.Message, e);
                }
            }
        }

        public string GetColState(DataGrid dataGrid)
        {
            try
            {
                var s = dataGrid.Columns.OrderBy(x => x.DisplayIndex).Select(x => string.Format("{0},{1},{2},{3}", x.GetValue(TagProperty), x.DisplayIndex, x.Width, x.Visibility));
                return string.Format("{{{{{0}}}}}", String.Join("},{", s.ToArray()));
            }
            catch (Exception e)
            {
                Level.Error.Log(Id, Config, e.Message, e);
                return null;
            }
        }

        //private
        private void LinkEvents(ColHelper colMap, string name)
        {
            //TODO rewrite
            if (colMap.ColType.Equals("PodEditPopup") && colMap.IsEnabled)
            {
                if (ColMaps.PodEditorPopupCols == null)
                {
                    ColMaps.PodEditorPopupCols = new Dictionary<string, string>();
                    _grid.DPods.PodChanged += DataGridBookedTrade_Update;
                }
                ColMaps.PodEditorPopupCols[name] = colMap.Links;
            }
            else if (colMap.ColType.Equals("QuotePopup") && colMap.IsEnabled)
            {
                if (ColMaps.QuotePopupCols == null)
                {
                    ColMaps.QuotePopupCols = new Dictionary<string, string>();
                    _grid.DPods.PodChanged += DataGridColQuote_Update;
                }
                ColMaps.QuotePopupCols[name] = colMap.Links;
            }
        }

        private async void PodEditorPopUp(IDPod dpod, string propertyName)
        {
            try
            {
                //TODO move to col
                await Task.Run(() =>
                {
                    object trade;
                    if (!Permissions.Get(dpod, Params.QuoteInstrument.ToString()).CanWrite) return;

                    if(dpod.TryGetObject(propertyName, out trade))
                        IOC.Singleton<IWindowHelper>().OpenAsync(Paths.Values["FolderSubViews"] + "PodEditor", "PodEditor", new object[,] { { "Pod", IOC.New<IPod>((object[,])trade.ToString().ToArray2d()) } }, Env, ShowType.Dispatch, "", "", true, true, true);
                });
            }
            catch (Exception e)
            {
                Level.Warning.Log(Id, Config, e.Message, e);
            }
        }

        private async void QuotePopUp(IDPod dPod, string propertyName)
        {
            try
            {
                //TODO move to col
                await Task.Run(() => 
                {
                    object quoteRequest, id;
                    if (!dPod.TryGetObject(propertyName, out quoteRequest)) 
                        return;

                    if (!dPod.TryGetObject(PodField.Id.ToString(), out id)) 
                        return;

                    var quote = IOC.New<IPod>(((object[,])quoteRequest.ToString().ToArray2d()));
                    var linkedId = quote[Params.LinkedId.ToString()].ToString();

                    if ((!string.IsNullOrEmpty(linkedId) && !linkedId.Equals(LinkedId)))
                        return;

                    if (Permissions.Get(Params.QuoteInstrument.ToString(), PodField.Id.ToString(), quote.Get(PodField.Id.ToString()).ToString()).CanWrite)
                        IOC.Singleton<IWindowHelper>().OpenAsync(Paths.Values["FolderSubViews"] + "QuotePopUpReply", "QuotePopUpReply", new object[,] { { "Quote", quote }, { "Instrument", dPod }, { "Reply", ColMaps.QuotePopupCols[propertyName] }, { "LinkedId", LinkedId } }, Env, ShowType.Central, "", "", false, false, true);
               });
            }
            catch (Exception e)
            {
                Level.Warning.Log(Id, Config, e.Message, e);
            }
        }

        //events
        private void DataGridColQuote_Update(object s, PropertyChangedEventArgs a) 
        { 
            if (ColMaps.QuotePopupCols.ContainsKey(a.PropertyName)) 
                QuotePopUp((IDPod)s, a.PropertyName);
        }      
        private void DataGridBookedTrade_Update(object s, PropertyChangedEventArgs a)
        {
            if (ColMaps.PodEditorPopupCols.ContainsKey(a.PropertyName))  
                PodEditorPopUp((IDPod)s, a.PropertyName); 
        }
    }
}
